# encoding: UTF-8
require_relative 'player'
require_relative 'card_dealer'

module Napakalaki  
  require "singleton"  
  class Napakalaki    
    include Singleton    
    attr_reader :current_monster, :dealer, :current_player, :players      
    
    def initialize
      @dealer=CardDealer.instance
      @players=Array.new
    end
    
    private #METODOS PRIVADOS    
    
    def init_players(names)
      for p in names
        @players << Player.new_name(p)  #Creo los jugadores pasandole el nombre y los añado al array jugadores  
      end
    end    
    
    def next_player
      indice = 0
      if(@current_player==nil)        #GENERO un numero aleatorio para elegir al primer jugador
        indice = rand(@players.size)
      else
        if(@current_player.equal?(@players.last)) #EN RUBY obj.equal?0bj) para comparar estado, no identidad
          indice=0
        else
          indice=@players.index(@current_player)+1
        end        
      end
      return @players.at(indice)
    end    
    
    def next_turn_allowed
      return @current_player.valid_state
    end
    
    public #METODOS PUBLICOS
    def develop_combat
      return self.current_player.combat(self.current_monster)
    end
    
    def discard_visible_treasures(treasures)
      treasures.each { |t|
        @current_player.discard_visible_treasure(t)
        @dealer.give_treasure_back(t)
      }
    end
    
    def discard_hidden_treasures(treasures)
      for t in treasures
        @current_player.discard_hidden_treasure(t)
        @dealer.give_treasure_back(t)
      end
    end
        
    def make_treasures_visible(treasures)
      treasures.each{ |t| @current_player.make_treasure_visible(t) }
    end
    
    def buy_levels(visible, hidden)
      return @current_player.buy_levels(visible, hidden)
    end
    
    def init_game(players)
      #llamo al metodo privado
      init_players(players) 
      @dealer.init_cards
      self.next_turn  
    end    
       
    def next_turn
      state_ok=false
      if(@current_player!=nil)
        state_ok=next_turn_allowed
      else
        state_ok=true
      end
      
      if(state_ok)
        @current_monster=@dealer.next_monster
        @current_player=next_player
        if(current_player.is_dead)
          @current_player.init_treasures
        end
      end      
      return state_ok      
    end
    
    def end_of_game(result)
      return result == :WINANDWINGAME
    end   
    
  end  
end